package org.example.controller;

import jakarta.annotation.Resource;
import org.example.pojo.Voice;
import org.example.service.VoiceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * 语音文件管理控制器
 *
 * @author rjs
 */

@RestController
@RequestMapping("/voice")
public class VoiceController {
    /**
     * 日志对象
     */
    private static final Logger logger = LoggerFactory.getLogger(VoiceController.class);
    /**
     * 语音文件服务
     */
    @Resource
    private VoiceService voiceService;

    /**
     * 上传语音文件
     *
     * @param file 语音文件
     * @return 是否上传成功
     */
    @PostMapping("/upload")
    public boolean save(@RequestParam("file") MultipartFile file) {
        try {
            Voice voice = new Voice();
            voice.setVoice(file.getBytes());
            return voiceService.save(voice);
        } catch (IOException e) {
            logger.error("上传语音时出错", e);
            return false;
        }
    }

    /**
     * 获取语音文件
     *
     * @param id 语音文件id
     * @return 语音文件和元数据
     */
    @GetMapping("/{id}")
    public ResponseEntity<byte[]> getVoiceById(@PathVariable Long id) {
        Optional<Voice> voiceOptional = Optional.ofNullable(voiceService.getById(id));
        if (voiceOptional.isPresent()) {
            Voice voice = voiceOptional.get();
            byte[] audio = voice.getVoice(); // Assuming getVoice() returns byte[]
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf("audio/mpeg"));
            return new ResponseEntity<>(audio, headers, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 更新语音文件
     *
     * @param voice 语音文件
     * @return 是否更新成功
     */
    @PutMapping
    public boolean updateById(@RequestBody Voice voice) {
        return voiceService.updateById(voice);
    }

    /**
     * 删除语音文件
     *
     * @param id 语音id
     * @return 是否删除成功
     */

    @DeleteMapping("/{id}")
    public boolean removeById(@PathVariable Long id) {
        return voiceService.removeById(id);
    }

    /**
     * 获取所有语音文件
     *
     * @return 语音文件列表
     */
    @GetMapping
    public List<Voice> listAll() {
        return voiceService.list();
    }
}

